package edu.cmu.javadb.index;

import java.lang.reflect.*;
import java.util.*;

import edu.cmu.javadb.Attribute;
import edu.cmu.javadb.IndexInfo;
import edu.cmu.javadb.RecordInfo;
import edu.cmu.javadb.exceptions.*;

public class IndexComparator<T> implements Comparator<T> {
	private IndexInfo indexInfo = new IndexInfo();
	
	public IndexComparator(IndexInfo indexInfo) {
		this.indexInfo = indexInfo;
	}
	
	@Override
	public int compare(T o1, T o2) {
		RecordInfo ri = RecordInfo.getRecordInfo(o1.getClass());

		//TODO: how to write index so no duplicate for existed field
		
		for (Attribute a : indexInfo.getAttributes()) {
			try {
				if (Comparable.class.isAssignableFrom(a.getValue(o1).getClass())) {
					Comparable v1 = (Comparable) a.getValue(o1);
					Comparable v2 = (Comparable) a.getValue(o2);
					
					int res = v1.compareTo(v2);
					if (res != 0)
						return res;
				} else {
					throw new RuntimeException(new NotComparableException());
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
}
